from requests.utils import requote_uri
from urllib.parse import quote
from sqlalchemy.orm import Session

from app.monitor_doris.handlers.monitor_doris_exclude_handler import MonitorDorisExcludeHandler
from app.tools_url_shorten.handlers import create_short_link
from setting import config


class MonitorDorisUrlHandler():
    """ url  Handler
    """
    
    def __init__(self):
        self.doris_log_url = config.DORIS_LOG_URL
        self.short_url = config.SHORT_URL
        self.doris_dbName = "log_warehouse"
        
        
    def get_service_short_url(self, db: Session, doris_table: str, service_info: dict):
        # 获取服务配置的屏蔽关键字
        exclude_keywords = MonitorDorisExcludeHandler().get_exclude_keywords(db, service_info["service_name"])
        filteredFields = [
            f"fields_app = '{service_info['service_name']}'",
            "level = 'ERROR'"
        ]
        for exclude_keyword in exclude_keywords:
            filteredFields.append(f"message not match_phrase '{exclude_keyword}'") 
            
        # 拼装青鸾前端页面的url
        startTime = quote(service_info["cst_begin_time"])
        endTime = quote(service_info["cst_end_time"])
        filteredFields = quote(str(filteredFields))
        qingluan_url = f"{self.doris_log_url}?dbName={self.doris_dbName}&tableName={doris_table}\
                        &searchTimeField=logtime&startTime={startTime}&endTime={endTime}\
                        &filteredFields={filteredFields}"
        
        #创建短连接码
        short_link = create_short_link(db, qingluan_url)
        short_url = f"{self.short_url}?short_link={quote(short_link)}"
        return short_url
    
    
    def get_custom_short_url(self, db: Session, doris_table: str, service_info: dict, custom_strategy:dict):
        filteredFields = [
            f"message match_phrase '{custom_strategy['keywords']}' "
        ]
        if custom_strategy['log_name']:
            filteredFields.append(f"fields_app = '{custom_strategy['log_name']}'")
            
        if custom_strategy['log_level']:
            filteredFields.append(f"level = '{custom_strategy['log_level']}'")
            
        # 拼装青鸾前端页面的url
        startTime = quote(service_info["cst_begin_time"])
        endTime = quote(service_info["cst_end_time"])
        filteredFields = quote(str(filteredFields))
        qingluan_url = f"{self.doris_log_url}?dbName={self.doris_dbName}&tableName={doris_table}\
                        &searchTimeField=logtime&startTime={startTime}&endTime={endTime}\
                        &filteredFields={filteredFields}"
                        
        #创建短连接码
        short_link = create_short_link(db, qingluan_url)
        short_url = f"{self.short_url}?short_link={quote(short_link)}"
        return short_url
        





if __name__ == '__main__':
    from common.database import SessionLocal
    session = SessionLocal()
    service_info={
        "service_name": "qingluan_doris",
        "cst_begin_time": "2024-03-07 09:57:55",
        "cst_end_time": "2024-03-07 10:57:55"
    }
    monitor_doris_url_handler = MonitorDorisUrlHandler()
    # res = monitor_doris_url_handler.get_service_short_url(session, "qingluan_doris", service_info)
    
    custom_strategy={
        "keywords": "mem",
        "log_name": "qingluan_doris",
        "log_level": "INFO"
    }
    res = monitor_doris_url_handler.get_custom_short_url(session, "qingluan_doris", service_info, custom_strategy)
    print(res)
